## SET UP FUNCTIONS ###############
error.rates <- function(yraw,yhatraw) {
  N = length(yraw)
  fp.rate <- sum((yhatraw!=yraw) * (1 - yraw)) / sum(1 - yraw)
  tp.rate <- sum((yhatraw==yraw) * (yraw)) / sum(yraw)
  tn.rate <- sum((yhatraw==yraw) * (1 - yraw)) / sum(1 - yraw)
  success.rate <- sum(yraw==yhatraw)/N
  er <- c("fp.rate"=fp.rate,
          "tp.rate"=tp.rate,
          "tn.rate"=tn.rate,
          "success.rate"=success.rate)
  return(er)
}

# Function to find most sensitive threshold
bestDT <- function(y,yhat,J) {
  dt_seq <- quantile(yhat,
                     probs = seq(1/J,1-1/J,1/J),
                     type = 2)
  # find starting value
  d <- 1
  predictions <- ifelse(yhat>dt_seq[d],1,0)
  errors <- error.rates(y,predictions) 
  while (.5>=errors["success.rate"]) {
    d = d + 100
    predictions <- ifelse(yhat>dt_seq[d],1,0)
    errors <- error.rates(y,predictions)
  }
  d = d - 100
  if (d<0) d <- 1
  predictions <- ifelse(yhat>dt_seq[d],1,0)
  errors <- error.rates(y,predictions)
  while (.5>=errors["success.rate"]) {
    d = d + 10
    predictions <- ifelse(yhat>dt_seq[d],1,0)
    errors <- error.rates(y,predictions)
  } 
  d = d - 10
  if (d<0) d <- 1
  predictions <- ifelse(yhat>dt_seq[d],1,0)
  errors <- error.rates(y,predictions)
  # Find lowest cutoff that keeps accuracy > 50%
  errors.lead = errors
  counter = 0
  while ((.5>=errors["success.rate"] | errors["tp.rate"] == errors.lead["tp.rate"])&counter<=30) {
    d = d + 1
    if (.5<=errors["success.rate"]) {counter = counter + 1}
    predictions <- ifelse(yhat>dt_seq[d],1,0)
    errors <- error.rates(y,predictions)
    predictions.lead <- ifelse(yhat>dt_seq[d+1],1,0)
    errors.lead <- error.rates(y,predictions.lead)        
  }
  DT=as.numeric(dt_seq[d])
  return(DT)
}
##! ###
mostaccDT <- function(y,yhat,J) {
  dt_seq <- quantile(yhat,
                     probs = seq(100/J,1-100/J,100/J),
                     type = 2)
  # find starting value
  dopt <- 0
  accopt <- 0
  d.index <- 0
  for (d in dt_seq) {
    d.index <- d.index + 1
    predictions <- ifelse(yhat>d,1,0)
    errors <- error.rates(y,predictions)
    if (errors["success.rate"] > accopt) {
      accopt <- errors["success.rate"]
      dopt <- d
      dopt.index <- d.index
    }
  }
  dt_seq <- quantile(yhat,
                     probs = seq(dopt.index*.1-90/J,dopt.index*.1+90/J,10/J),
                     type = 2)
  dopt <- 0
  accopt <- 0
  d.index <- dopt.index*10-J/100
  for (d in dt_seq) {
    d.index <- d.index + 1
    predictions <- ifelse(yhat>d,1,0)
    errors <- error.rates(y,predictions)
    if (errors["success.rate"] > accopt) {
      accopt <- errors["success.rate"]
      dopt <- d
      dopt.index <- d.index
    }
  }
  dt_seq <- quantile(yhat,
                     probs = seq(dopt.index*.01-(9/J),dopt.index*.01+(9/J),1/(J)),
                     type = 2)
  dopt <- 0
  accopt <- 0
  for (d in dt_seq) {
    d.index <- d.index + 1
    predictions <- ifelse(yhat>d,1,0)
    errors <- error.rates(y,predictions)
    if (errors["success.rate"] > accopt) {
      accopt <- errors["success.rate"]
      dopt <- d
    }
  }
  DT=as.numeric(dopt)
  return(DT)
}

Rdev <- function(y,yhat) {
  num <- y*log(yhat)-y*log(mean(y))-(yhat-mean(y))
  num[yhat == 0] <- -y[yhat == 0]*log(mean(y))+mean(y)
  denom <- y*log(y)-y*log(mean(y))
  denom[y == 0] <- -y[y == 0]*log(mean(y))
  R2 <- sum(num)/sum(denom)
  return(R2)
}

# Prints 2 Panel Tables to LaTeX
print.texfragment <- function(table, file, filepath, head.width = '1.5', head.height = '2') {
  n_panel = dim(table)[1]
  n_row = dim(table)[2]
  n_column = dim(table)[3]
  out <- paste("\\begin{tabular}{l",
               paste(rep('c',n_column), 
                     collapse=""),
               "} \\hline \\hline",
               sep = "")
  line <- paste(' & \\begin{minipage}[t][',
                head.height,
                'cm][b]{',
                head.width,
                'cm}\\begin{center} ',
                paste(dimnames(table)[[3]], 
                      collapse=paste('\\end{center}\\end{minipage} & \\begin{minipage}[t][',
                                     head.height,
                                     'cm][b]{',
                                     head.width,
                                     'cm}\\begin{center} ', sep='')),
                '\\end{center}\\end{minipage} \\\\',
                sep='')
  out <- c(out, line)
  line = " "
  for (k in 1:n_column) {
    line = paste(line,
                 "& (",
                 format(k),
                 ") ",
                 sep="")
  }
  line = paste(line,
               " \\\\",
               sep="")
  out <- c(out, line)
  
  out <- c(out, 
           paste("\\cline{2-",
                 format(n_column + 1),
                 "}",
                 sep=""))
  out <- c(out,
           paste(paste(rep(" & ", n_column),
                       collapse=""),
                 " \\\\",
                 sep=""))
  
  for (i in 1:n_panel) {
    out <- c(out,
             paste(paste(rep(" & ", n_column),
                         collapse=""),
                   " \\\\",
                   sep=""))
    out <- c(out,
             paste(" & \\multicolumn{",
                   factor(n_column),
                   "}{c}{",
                   dimnames(table)[[1]][i],
                   "} \\\\ \\cline{2-",
                   format(n_column + 1),
                   "}",
                   sep=''))
    for (j in 1:n_row) {
      line <- paste(paste(c(dimnames(table)[[2]][j],
                            format(table[i,j,], 
                                   digits=3)),
                          collapse=' & '), 
                    ' \\\\', sep='')
      out <- c(out, line)
    }
  }
  out <- c(out, "\\hline\\hline\\end{tabular}")
  write(out,file=paste(filepath,'/',
                       file,'.tex',sep=''))
}

printA1 <- function(table,
                    breaks,
                    filepath,
                    file,
                    metric.key,
                    head.width = '1.5', 
                    head.height = '2') {
  subpanels = length(breaks)+1
  panels = dim(table)[2]
  metrics = dimnames(table)[[4]]
  n_row = dim(table)[4]
  n_column = dim(table)[3]
  countries <- dimnames(table)[[1]]
  out <- paste("\\begin{tabular}{l",
               paste(rep('c',n_column*2), 
                     collapse=""),
               "} \\hline \\hline",
               sep = "")
  line <- paste0("  & \\multicolumn{5}{c}{{",
                 countries[1],
                 "}} & \\multicolumn{5}{c}{{",
                 countries[2],
                 "}} \\\\ \\cmidrule(lr){2-",
                 1 + n_column,
                 "} \\cmidrule(lr){",
                 2+n_column,"-", 1 + n_column*2, "}")
  out <- c(out, line)
  line <- paste(' & \\begin{minipage}[t][',
                head.height,
                'cm][b]{',
                head.width,
                'cm}\\begin{center} ',
                paste(c(dimnames(table)[[3]],
                        dimnames(table)[[3]]), 
                      collapse=paste('\\end{center}\\end{minipage} & \\begin{minipage}[t][',
                                     head.height,
                                     'cm][b]{',
                                     head.width,
                                     'cm}\\begin{center} ', sep='')),
                '\\end{center}\\end{minipage} \\\\',
                sep='')
  out <- c(out, line)
  # Add column numbers
  line = " "
  for (k in 1:(2*n_column)) {
    line = paste(line,
                 "& (",
                 format(k),
                 ") ",
                 sep="")
  }
  line = paste0(line,
                " \\\\",
                "\\cmidrule(lr){2-",
                1 + n_column,
                "} \\cmidrule(lr){",
                2+n_column,"-", 1 + n_column*2, "}")
  out <- c(out, line, "\\\\")
  for (v in dimnames(table)[[2]]) {
    line = paste0("\\\\ & \\multicolumn{",
                  n_column*2,
                  "}{c}{\\textbf{",
                  v,
                  "}} \\\\ \\cmidrule(lr){",
                  2,"-", 1 + n_column*2, "} \\\\ ")
    out <- c(out,line)
    for (m in metrics[1:(breaks[1]-1)]) {
      line <- paste(c(metric.key[m],
                      format(c(table[countries[1],
                                           v,
                                           ,m],
                               table[countries[2],
                                           v,
                                           ,m]),
                             digits=3)),
                    collapse = " & ")
      out <- c(out, paste0(line, " \\\\"))
    }
    for (p in 1:length(breaks)) {
      if (names(breaks)[p] == "") {
        out <- c(out,"\\\\ ")
      } else {
        out <- c(out,"\\\\ ",
                 paste0(" & \\multicolumn{",
                        n_column*2,
                        "}{c}{\\emph{",
                        names(breaks)[p],
                        "}} \\\\ \\cmidrule(lr){",
                        2,"-", 1 + n_column*2, "} \\\\ ")
                 
        )
      }
      
      for (m in metrics[breaks[p]:(c(breaks,
                                     length(metrics)+1)[p+1] - 1
      )]) {
        line <- paste(c(metric.key[m],
                        format(c(table[countries[1],
                                             v,
                                             ,m],
                                 table[countries[2],
                                             v,
                                             ,m]),
                               digits=3)),
                      collapse = " & ")
        out <- c(out, paste0(line, " \\\\"))
      }
      out <- c(out, "\\hline ")
    }
  }
  out <- c(out, "\\hline\\end{tabular}")
  write(out,file=paste(filepath,'/',
                       file,'.tex',sep=''))
}

printA3 <- function(table, file, filepath, header="", 
                    head.width = '1.5', head.height = '2') {
  n_panel = dim(table)[1]
  n_row = dim(table)[2]
  n_column = dim(table)[3]
  out <- paste("\\begin{tabular}{l",
               paste(rep('c',n_column), 
                     collapse=""),
               "} \\hline \\hline",
               sep = "")
  line <- paste0(' & \\multicolumn{',
                 n_column,
                 "}{c}{",
                 header,
                 "} \\\\ \\cmidrule{2-",
                 1+n_column,
                 "}")
  out <- c(out,
           line)
  line <- paste(' & \\begin{minipage}[t][',
                head.height,
                'cm][b]{',
                head.width,
                'cm}\\begin{center} ',
                paste(dimnames(table)[[3]], 
                      collapse=paste('\\end{center}\\end{minipage} & \\begin{minipage}[t][',
                                     head.height,
                                     'cm][b]{',
                                     head.width,
                                     'cm}\\begin{center} ', sep='')),
                '\\end{center}\\end{minipage} \\\\',
                sep='')
  out <- c(out, line)
  line = " "
  for (k in 1:n_column) {
    line = paste(line,
                 "& (",
                 format(k),
                 ") ",
                 sep="")
  }
  line = paste(line,
               " \\\\",
               sep="")
  out <- c(out, line)
  
  out <- c(out, 
           paste("\\cline{2-",
                 format(n_column + 1),
                 "}",
                 sep=""))
  out <- c(out,
           paste(paste(rep(" & ", n_column),
                       collapse=""),
                 " \\\\",
                 sep=""))
  
  for (i in 1:n_panel) {
    out <- c(out,
             paste(paste(rep(" & ", n_column),
                         collapse=""),
                   " \\\\",
                   sep=""))
    out <- c(out,
             paste(" & \\multicolumn{",
                   factor(n_column),
                   "}{c}{",
                   dimnames(table)[[1]][i],
                   "} \\\\ \\hline",
                   sep=''))
    for (j in 1:n_row) {
      line <- paste(paste(c(dimnames(table)[[2]][j],
                            format(table[i,j,], 
                                   digits=ifelse(j==1,4,ifelse(i==1,
                                                                2,
                                                                3)))),
                          collapse=' & '), 
                    ' \\\\', sep='')
      out <- c(out, line)
    }
    out <- c(out, " \\hline")
  }
  out <- c(out, "\\hline\\end{tabular}")
  write(out,file=paste(filepath,'/',
                       file,'.tex',sep=''))
}

printA4 <- function(table, file, filepath) {
  n_panel = dim(table)[1]
  n_row = dim(table)[2]
  out <- paste("\\begin{tabular}{l",
               paste(rep('c',n_panel), 
                     collapse=""),
               "} \\hline \\hline \\\\ ",
               sep = "")
  line <- paste0(' & ',
                 paste(dimnames(table)[[1]],
                       collapse=' & '),
                 " \\\\ ")
  out <- c(out,
           line)
  line = " "
  for (k in 1:n_panel) {
    line = paste(line,
                 "& (",
                 format(k),
                 ") ",
                 sep="")
  }
  line = paste(line,
               " \\\\ \\hline",
               sep="")
  out <- c(out, line)
  for (j in 1:n_row) {
      line <- paste(paste(c(dimnames(table)[[2]][j],
                            format(table[,j], 
                                   digits=ifelse(j<3,4,2))),
                          collapse=' & '), 
                    ' \\\\', sep='')
      out <- c(out, line)
  }
  out <- c(out, "\\hline \\hline\\end{tabular}")
  write(out,file=paste(filepath,'/',
                       file,'.tex',sep=''))
}

printA5 <- function(table, file, filepath,
                    head.width = '1.5', head.height = '2') {
  n_row = dim(table)[1]
  n_column = dim(table)[2]
  out <- paste("\\begin{tabular}{l",
               paste(rep('c',n_column), 
                     collapse=""),
               "} \\hline \\hline \\\\ ",
               sep = "")
  line <- paste0(' & \\begin{minipage}[t][',
                 head.height,
                 'cm][b]{',
                 head.width,
                 'cm}\\begin{center} ',
                 paste(dimnames(table)[[2]], 
                       collapse=paste('\\end{center}\\end{minipage} & \\begin{minipage}[t][',
                                      head.height,
                                      'cm][b]{',
                                      head.width,
                                      'cm}\\begin{center} ', sep='')),
                 '\\end{center}\\end{minipage} \\\\')
  
  out <- c(out,
           line)
  line = " "
  for (k in 1:n_column) {
    line = paste(line,
                 "& (",
                 format(k),
                 ") ",
                 sep="")
  }
  line = paste0(line,
                " \\\\ \\cmidrule{2-",
                1+n_column, "} \\\\ \\\\")
  out <- c(out, line)
  line = paste0(" & \\multicolumn{", n_column,
                "}{c}{Indonesia, 2008-2014} \\\\ \\cmidrule{2-",
                1+n_column, "}")
  out <- c(out, line)
  
  for (j in 1:n_row) {
    line <- paste(paste(c(dimnames(table)[[1]][j],
                          format(table[j,], 
                                 digits=3)),
                        collapse=' & '), 
                  ' \\\\', sep='')
    out <- c(out, line)
  }
  out <- c(out, "\\hline \\end{tabular}")
  write(out,file=paste(filepath,'/',
                       file,'.tex',sep=''))
}


printB1 <- function(table,
                    filepath,
                    file,
                    head.width = '1.5', 
                    head.height = '2') {
  metrics = dimnames(table)[[4]]
  n_row = dim(table)[4]
  n_column = dim(table)[3]
  countries <- dimnames(table)[[1]]
  out <- paste("\\begin{tabular}{l",
               paste(rep('c',n_column), 
                     collapse=""),
               "} \\hline \\hline",
               sep = "")
  line <- paste(' & \\begin{minipage}[t][',
                head.height,
                'cm][b]{',
                head.width,
                'cm}\\begin{center} ',
                paste(c(dimnames(table)[[3]]), 
                      collapse=paste('\\end{center}\\end{minipage} & \\begin{minipage}[t][',
                                     head.height,
                                     'cm][b]{',
                                     head.width,
                                     'cm}\\begin{center} ', sep='')),
                '\\end{center}\\end{minipage} \\\\',
                sep='')
  out <- c(out, line)
  # Add column numbers
  line = " "
  for (k in 1:(n_column)) {
    line = paste(line,
                 "& (",
                 format(k),
                 ") ",
                 sep="")
  }
  line = paste0(line,
                " \\\\",
                "\\cmidrule(lr){2-",
                1 + n_column,
                "}")
  out <- c(out, line, "\\\\")
  for (v in dimnames(table)[[2]]) {
    line = paste0("\\\\ & \\multicolumn{",
                  n_column,
                  "}{c}{\\textbf{",
                  v,
                  "}} \\\\ \\cmidrule(lr){",
                  2,"-", 1 + n_column, "} ")
    out <- c(out,line)
    for (c in countries) {
      line = paste0(" & \\multicolumn{",
                    n_column,
                    "}{c}{\\textbf{",
                    c,
                    "}} \\\\ \\cmidrule(lr){",
                    2,"-", 1 + n_column, "} ")
      out <- c(out,line)
      for (m in metrics) {
        line <- paste(c(m,
                        format(c(table[c,
                                       v,,
                                       m]),
                               digits=3)),
                      collapse = " & ")
        out <- c(out, paste0(line, " \\\\"))
      }
    }
    out <- c(out, " \\hline")
  }
  out <- c(out, "\\hline\\end{tabular}")
  write(out,file=paste(filepath,'/',
                       file,'.tex',sep=''))
}

printC44 <- function(table,
                    filepath,
                    file,
                    shock_key) {
  vars <- dimnames(table)[[1]]
  shocks <- dimnames(table)[[2]]
  n_shocks <- length(shocks)
  asterisks <- array("",
                     dim = dim(table),
                     dimnames = dimnames(table))
  asterisks[table[,,,'ast'] < .1] <- "*"
  asterisks[table[,,,'ast'] < .05] <- "**"
  asterisks[table[,,,'ast'] < .01] <- "***"
  out <- paste("\\begin{tabular}{l",
               paste(rep('c',n_shocks*2), 
                     collapse=""),
               "} \\hline \\hline",
               sep = "")
  out <- c(out,
           paste0(' & \\multicolumn{',
                  n_shocks*2,'}{c}{Type of Shock} \\\\ '))
  line <- paste0(" & \\multicolumn{2}{c}{",
                 paste(shock_key[shocks],
                       collapse="} & \\multicolumn{2}{c}{"),
                 "} \\\\ ")
  out <- c(out,
           line)
  line = ""
  for (i in 1:n_shocks) {
    line <- paste0(line,
                   "\\cmidrule(lr){",
                   i*2, "-", i*2+1,"} ")
  }
  out <- c(out, 
           line, "\\\\")
  line <- "Dep. Var.: conflict in"
  for (i in 1:n_shocks) {
    line <- paste0(line,
                   " & $t$ & $t+1$ ")
  }
  out <- c(out, 
           line, "\\\\ \\\\")
  for (v in vars) {
    out <- c(out,
             paste0(' & \\multicolumn{',
                    n_shocks*2,'}{c}{\\textbf{',
                    v,
                    '}} \\\\ '))
    out <- c(out,
             paste0("\\cmidrule(lr){",
                    2, "-", n_shocks*2+1,"} "))
    line1 <- "shock in $t$ "
    line2 <- "  "
    for (s in shocks) {
      line1 <- paste0(line1, 
                      " & ",
                     paste(paste0(round(table[v,s,,'b'],
                                        digits=3),
                                  asterisks[v,s,,'b']),
                           collapse = " & "))
      line2 <- paste0(line2,
                      " & (",
                      paste(round(table[v,s,,'se'],
                                         digits=3),
                            collapse = ") & ("),
                      ")")
    }  
    out <- c(out,
             line1,
             "\\\\",
             line2,
             "\\\\ \\hline ")
    
  }
  out <- c(out, "\\hline\\end{tabular}")
  write(out,file=paste(filepath,'/',
                       file,'.tex',sep=''))  
}
   
library(stringr)
clean_indo_varname <- function(x) {
  xnew = x
  for (ending in c(", current year (t)",
                   ", most recent Podes",
                   ", 2005 Podes")) {
    for (z in nchar(ending):5) {
      #xnew = strsplit(xnew, substr(ending, 1, z))[[1]][1]
      xnew = str_replace_all(xnew, fixed(substr(ending, 1, z)), "")
    }
  }
  #xnew = str_replace_all(xnew, fixed("\\"), fixed("\\\\"))
  return(xnew)
}


panelvar_ratio <- function(variable,
                           groupvariable) {
  # find out how many values the group variable can take
  groupvariable2 <- as.factor(groupvariable)
  df = data.frame(x=variable,
                  g=groupvariable2)
  df$dev = df$x - transform(df, mean = ave(x, g, FUN = mean))$mean + mean(df$x)
  means <- aggregate(variable, list(groupvariable2), mean)$x
  # calculate the between-groups variance
  Vw <- sd(df$dev)
  Vb <- sd(means)
  return(Vw/Vb)
}

make_summary_table <- function(filename, 
                               ds, xlist, label.list, 
                               dataset_key, group, outcome) {
  out <- c('\\begin{tabular}{l|cccc|cc|cc}',
           ' & (1) & (2) & (3) & (4) & (5) & (6) & (7) & (8) \\\\',
           ' & Mean & Median & 25$^{th}$ Pct. & 75$^{th}$ Pct. ',
           '& \\begin{minipage}{.9cm}\\center Corr. w/ Any\\end{minipage} ',
           '& \\begin{minipage}{1.4cm}\\center Within/ Between Var.\\end{minipage}',
           '& \\% Miss & Source \\\\ \\hline'
  )
  for (x in xlist) {
    if (!is.element(substr(x, nchar(x)-1,
                           nchar(x)),
                    c('L1', 'L2', 'L3')) &
        substr(x, 1, 3) == 'rhs') {
      line <- clean_indo_varname(label.list[names(ds)==x])
      line <- paste0(line,
                     ' & ',
                     sprintf(mean(ds[,x]), fmt = '%#.2f'))
      line <- paste0(line,
                     ' & ',
                     sprintf(median(ds[,x]), fmt = '%#.2f'))
      line <- paste0(line,
                     ' & ',
                     sprintf(quantile(ds[,x], .25), fmt = '%#.2f'))
      line <- paste0(line,
                     ' & ',
                     sprintf(quantile(ds[,x], .75), fmt = '%#.2f'))
      
      line <- paste0(line,
                     ' & ',
                     sprintf(cor(ds[,x],
                                 ds[, outcome]),
                             fmt = '%#.2f'))
      line <- paste0(line,
                     ' & ',
                     sprintf(panelvar_ratio(ds[,x],
                                            ds[, group]),
                             fmt = '%#.2f'))
      
      mi_var <- gsub("rhs_", 
                     "mi_", 
                     x)
      if (mi_var %in% names(ds)) {
        line <- paste0(line,
                       ' & ',
                       sprintf(mean(ds[,mi_var])*100,
                               fmt = '%#.1f'))
      } else {
        line <- paste0(line,
                       ' & ',
                       sprintf(0,
                               fmt = '%#.1f'))
        print(paste0('Missing ', mi_var))
      }      
      line <- paste0(line,
                     ' & ',
                     dataset_key[x],
                     " \\\\")
      out <- c(out,
               line)
    }
  }
  out <- c(out,
           "\\hline\\hline",
           "\\end{tabular}")
  
  write(out,file=filename)
  
}

make_summary_table_colo <- function(filename, 
                               ds, xlist, label.list, 
                               dataset_key, group, outcome) {
  out <- c('\\begin{tabular}{l|cccc|cc|cc}',
           ' & (1) & (2) & (3) & (4) & (5) & (6) & (7) & (8) \\\\',
           ' & Mean & Median & 25$^{th}$ Pct. & 75$^{th}$ Pct. ',
           '& \\begin{minipage}{.9cm}\\center Corr. w/ Any\\end{minipage} ',
           '& \\begin{minipage}{1.4cm}\\center Within/ Between Var.\\end{minipage}',
           '& \\% Miss & Source \\\\ \\hline'
  )
  for (x in xlist) {
    if (!is.element(substr(x, nchar(x)-1,
                           nchar(x)),
                    c('L1', 'L2', 'L3')) &
        substr(x, 1, 3) == 'rhs') {
      line <- clean_indo_varname(label.list[names(ds)==x])
      line <- paste0(line,
                     ' & ',
                     sprintf(mean(ds[,x]), fmt = '%#.2f'))
      line <- paste0(line,
                     ' & ',
                     sprintf(median(ds[,x]), fmt = '%#.2f'))
      line <- paste0(line,
                     ' & ',
                     sprintf(quantile(ds[,x], .25), fmt = '%#.2f'))
      line <- paste0(line,
                     ' & ',
                     sprintf(quantile(ds[,x], .75), fmt = '%#.2f'))
      
      line <- paste0(line,
                     ' & ',
                     sprintf(cor(ds[,x],
                                ds[, outcome]),
                            fmt = '%#.2f'))
      line <- paste0(line,
                     ' & ',
                     sprintf(panelvar_ratio(ds[,x],
                                            ds[, group]),
                             fmt = '%#.2f'))
      mi_var <- gsub("L0",
                     "",
                     gsub("rhs_", 
                          "mi_", 
                          x))
      if (mi_var %in% names(ds)) {
        line <- paste0(line,
                       ' & ',
                       sprintf(mean(ds[,mi_var])*100,
                                fmt = '%#.1f'))
      } else {
        line <- paste0(line,
                       ' & ',
                       sprintf(0,
                              fmt = '%#.1f'))
        print(paste0('Missing ', mi_var))
      }
      line <- paste0(line,
                     ' & ',
                     dataset_key[x],
                     " \\\\")
      out <- c(out,
               line)
    }
  }
  out <- c(out,
           "\\hline\\hline",
           "\\end{tabular}")
  
  write(out,file=filename)
  
}
#--------------------------------